package com.xxxx.comment.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.comment.constants.RedisConstants;
import com.xxxx.comment.entity.ShopType;
import com.xxxx.comment.entity.dto.Result;
import com.xxxx.comment.mapper.ShopTypeMapper;
import com.xxxx.comment.service.IShopTypeService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService
{
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryShopList()
    {
//        Map<Object, Object> shopMap = stringRedisTemplate.opsForHash()
//                .entries(RedisConstants.CACHE_SHOP_LIST_KEY);
//        if (!shopMap.isEmpty())
//        {
//            // 如果 Redis 缓存中存在对应的数据
//            List<ShopType> typeList = shopMap.values().stream()
//                    .map(value -> JSONUtil.toBean(value.toString(), ShopType.class))
//                    .collect(Collectors.toList());
//            return Result.ok(typeList);
//        }
//        // 如果 Redis 缓存中不存在对应的数据
//        List<ShopType> typeList = query().orderByAsc("sort").list();
//        System.out.println(typeList);
//        Map<String, String> typeMap = typeList.stream()
//                .collect(Collectors.toMap(shop -> shop.getId().toString(), shop -> JSONUtil.toJsonStr(shop).toString()));
//        stringRedisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_LIST_KEY, typeMap);

        String shops = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_LIST_KEY);
        if (StrUtil.isNotBlank(shops))
        {
            List<ShopType> list = JSONUtil.parseArray(shops).toList(ShopType.class);
            return Result.ok(list);
        }
        // 如果 Redis 缓存中不存在对应的数据
        List<ShopType> typeList = query().orderByAsc("sort").list();
        String jsonStr = JSONUtil.toJsonStr(typeList);
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_LIST_KEY, jsonStr);

        return Result.ok(typeList);
    }
}
